package redenvelope

import (
	"errors"
	"fmt"
	"math/rand"
	"sort"
	"time"
)

func GetRandomRedEnvelopes(total int, num int) (data []int, err error) {
	if num > total {
		return nil, errors.New("num is bigger than total")
	}
	rand.Seed(time.Now().Unix())
	//n个人分红包，则用n-1个点把total分成n份
	exsitsFlag := make(map[int]struct{}, num-1)
	points := []int{0}
	var envelops []int
	for i := 0; i < num-1; i++ {
		n := rand.Intn(total-1) + 1
		if _, exsits := exsitsFlag[n]; exsits {
			// 重复
			i--
			continue
		}
		exsitsFlag[n] = struct{}{}
		points = append(points, n)
	}
	sort.Ints(points)
	fmt.Println(points)
	for i := 1; i < num; i++ {
		value := points[i] - points[i-1]
		envelops = append(envelops, value)
	}
	envelops = append(envelops, total-points[num-1])
	sort.Ints(envelops)
	for i := num - 1; i >= 0; i-- {
		data = append(data, envelops[i])
	}
	return data, nil
}
